package cn.com.aiton.common.utils;

import cn.com.aiton.common.model.ServiceResult;
import cn.com.aiton.common.model.gbt209992007.GbtStagePatternDomain;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/6.
 */
public class JsonToStagePatternListUtil {

    private static final Logger LOG =
            LoggerFactory.getLogger(JsonToStagePatternListUtil.class);

    public static ServiceResult stagePatternList(String json){
        ServiceResult message = new ServiceResult();
        try{
            JSONArray array = new JSONArray(json);
            List<GbtStagePatternDomain> list = new ArrayList<>();
            for(int i=0;i<array.length();i++){
                JSONObject object = array.getJSONObject(i);
                GbtStagePatternDomain command = new GbtStagePatternDomain();
                command.setStagePatternNumber(object.getInt("id"));
                command.setStageNumber(object.getInt("stageId"));
                command.setGreenTime(object.getInt("greenTime"));
                command.setRedTime(object.getInt("redTime"));
                command.setYellowTime(object.getInt("yellowTime"));
                command.setOption(object.getInt("option"));
                command.setAllowPhase(listToInt(objectToList(object.getJSONArray("phaseList"))));
                command.setPhaseList(objectToList(object.getJSONArray("phaseList")));
                list.add(command);
            }

            message.setObject(list);
            message.setSuccess(true);
            return message;
        }catch (Exception e){
            LOG.error(e.getMessage(),e);
            message.setSuccess(false);
            message.setMessage("数据转换出错");
            return message;
        }
    }

    private static int listToInt(List<Integer> list){
        int i = 0;

        for(int j:list){
            if (j!=0) {
                i = i | (1 << (j - 1));
            }
        }

        return i;
    }

    private static List<Integer> objectToList(JSONArray array) throws JSONException {

        List<Integer> list = new ArrayList<>();

        for(int i=0;i<array.length();i++){
            list.add(array.getInt(i));
        }

        return list;
    }
}
